package com.czl.lunt.service.impl;

import com.czl.lunt.Exception.ApplicationException;
import com.czl.lunt.common.Result;
import com.czl.lunt.common.ResultCode;
import com.czl.lunt.dao.BoardMapper;
import com.czl.lunt.model.Board;
import com.czl.lunt.service.BoardService;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Slf4j
@Service
public class BoardServiceImpl implements BoardService {

    @Autowired
    private BoardMapper boardMapper;

    @Override
    public List<Board> selectByNum(Integer num) {
        if(num < 0){
            log.info("num = {} ,参数出现异常", num);
            throw new ApplicationException("参数异常");
        }
        return boardMapper.selectByNum(num);
    }

    @Override
    public void addOneArticleById(@NonNull Long id) {
        if(id < 0){
            log.info("板块数量小于0");
            throw new ApplicationException("板块数量小于0");
        }

        Board board = boardMapper.selectByPrimaryKey(id);

        if(board == null){
            log.info("板块数据异常");
            throw new ApplicationException("板块数据异常");
        }
        Board updateBoard = new Board();
        updateBoard.setId(board.getId());
        updateBoard.setArticleCount(board.getArticleCount() + 1);

        int end = boardMapper.updateByPrimaryKeySelective(updateBoard);

        if(end != 1){
            log.info("受影响行数不等于1");
            throw new ApplicationException(Result.failed(ResultCode.FAILED_BOARD_BANNED));
        }
    }

    @Override
    public void subOneArticleById(@NonNull Long id) {
        if(id < 0){
            log.info("板块数量小于0");
            throw new ApplicationException("板块数量小于0");
        }

        Board board = boardMapper.selectByPrimaryKey(id);

        if(board == null){
            log.info("板块数据异常");
            throw new ApplicationException("板块数据异常");
        }
        Board updateBoard = new Board();
        updateBoard.setId(board.getId());

        int count = board.getArticleCount() - 1;
        log.info("======================================={}", board.getName());
        log.info("board.getArticleCount() = {}", board.getArticleCount());
        log.info("count = {}------------------------------", count);
        if(count < 0){
            log.info("别删了 ，已经没有帖子啦");
            throw new ApplicationException("别删了 ，已经没有帖子啦");
        }
        updateBoard.setArticleCount(count);

        int end = boardMapper.updateByPrimaryKeySelective(updateBoard);

        if(end != 1){
            log.info("受影响行数不等于1");
            throw new ApplicationException(Result.failed(ResultCode.FAILED_BOARD_BANNED));
        }


    }

    @Override
    public Board selectById(@NonNull Long id) {
        return boardMapper.selectByPrimaryKey(id);
    }
}
